import ala from '@/service/ala.js'
import api from '@/service/api.js'
import Vue from 'vue'
import {
	HubConnectionBuilder,
	LogLevel
} from '@microsoft/signalr'

/**
	* 定义所有客户端，监听的方法，和服务端一一对应
   从中心调用客户端方法
   和后台ClientHubType对应
	*/
let clients = ['SystemOnlineCount', // 系统在线人数
	'ImChatReceiveMessage', // im 聊天接收消息
	'ImChatUnReadCount', // 未读消息数量
	'ImChatConversation', // 即时通讯,会话信息
	'NotificationPush' //推送消息到状态栏
]

/**
	* signlar开始链接
	*/
export async function hubConnect() {
	var clientHubUrl = ala.host + 'ClientHub'
	var token = encodeURIComponent(JSON.stringify(api.imUser()))
	const connection = new HubConnectionBuilder().withUrl(clientHubUrl, {
		accessTokenFactory: () => token
	}).withAutomaticReconnect().configureLogging(LogLevel.Error).build()
	connection.keepAliveIntervalInMilliseconds = 3000
	connection.serverTimeoutInMilliseconds = 16000
	connection.onreconnected(connectionId => {
		console.error('onreconnected.')
	})
	connection.onreconnecting(error => {
		console.error('onreconnecting.', error)
	})
	connection.onclose(async () => {
		console.error('SignalR Closed.')
		await start()
	})
	// 监听所有的方法
	clients.forEach(element => {
		connection.on(element, async function (data) {
			await Vue.prototype.$bus.$emit(element, data)
		})
	})
	async function start() {
		try {
			//	await connection.start()
		} catch (err) {
			setTimeout(start, 5000)
		}
	}
	await start()
}